package com.xw.lora.controller;

import com.alibaba.fastjson.JSON;
import com.xw.lora.enums.ResultCodeEnum;
import com.xw.lora.pojo.Updata;
import com.xw.lora.service.UpdataService;
import com.xw.lora.vo.Result;
import com.xw.lora.vo.UpData;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

/**
 * @ClassName TestController
 * @Author liu zhiyong
 * @Date 2020/9/24 16:59
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/updata")
public class UpdataController {

    @Autowired
    private UpdataService updataService;

    @RequestMapping("/receiveData")
    public String getUpData(@RequestBody UpData upData) {
        String dataStr = upData.getData();
        Base64.Decoder decoder = Base64.getDecoder();
        String data = "";
        try {
            data = new String(decoder.decode(dataStr), "UTF-8");//解码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        upData.setData(data);

        String data2 = "";
        try {
            data2 = JSON.toJSONString(upData);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("对象转换json失败...");
        }
        System.out.println("接收到的上行数据：" + data2);

        //存入数据库
        updataService.save(data2);

        return "ok";
    }

    @RequestMapping("/test")
    public String test(){

        return "hello lora...";
    }

    /**
     * 查询updata列表，topN
     * @Author liu zhiyong
     * @Date 2020/10/22 11:26
     * @param topN 最新的n条数据
     * @return com.xw.lora.vo.Result
     **/
    @RequestMapping("/list")
    public Result list(Integer topN){

        if(topN == null){
            return Result.fail(ResultCodeEnum.PARAM_VAL_IS_EMPTY);
        }

        List<Updata> list = updataService.list(topN);

        return Result.ok(list);
    }

}
